/**
 *
 */
package com.comba.nutz.boot.demo.handler;

import com.comba.nutz.boot.demo.entity.ResultModel;
import org.nutz.json.Json;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 *
 * @author zhailiang
 */
@Component("authenctiationFailureHandler")
public class AuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        ResultModel resultModel = new ResultModel();

        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            resultModel.setMessage("用户名或密码错误!");
            resultModel.setCode("100");
        } else if (exception instanceof DisabledException) {
            resultModel.setMessage("账户被禁用，登录失败，请联系管理员!");
            resultModel.setCode("401");
        } else {
            resultModel.setMessage("登录失败!");
            resultModel.setCode("-1");
        }

        response.getWriter().write(Json.toJson(resultModel));
    }

}
